package app.controller;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;


import app.config.Config;
import app.domain.Result;
import app.domain.User;
import app.domain.UserInfo;
import app.service.UserInfoService;
import app.service.UserService;
import app.utils.MD5Util;


@Controller
public class UserController {
	public static Logger logger=LogManager.getLogger(UserController.class);
	
	@Autowired
	private UserInfoService userInfoService;
	@Autowired
	private UserService userService;
	
	@RequestMapping(value="login",method=RequestMethod.POST)
	public String login(HttpSession session,String accountName,String token,Model model){
		String url="index";
		UserInfo userInfo=userInfoService.getUserInfo(accountName);
		if(userInfo!=null&&userInfo.getStatus()==0){
		    if(token.toUpperCase().equals(userInfo.getPassword().toUpperCase())){
			   session.setAttribute("userInfo", userInfo);
			   switch(userInfo.getRole()){
			     case Config.ROLE_ADMIN:url="admin/admin";break;
			     case Config.ROLE_USER:url="user/user";break;
			     case Config.ROLE_WORKER:url="worker/worker";break;
			   }
		    } 
	     }
		else{
			model.addAttribute("msg", "帐户名或密码错误");
			return "index";
		}
		return url;
	}
	
	
	@RequestMapping("logout")
	public String logout(HttpSession session){
	    session.invalidate();
		return "redirect:/index";
	}
	
	@RequestMapping("registe")
	public String regist(){
		return "register";
	}
	
	@RequestMapping("addUserInfo")
	@ResponseBody
	public Result registe(UserInfo userInfo){
		Result result=new Result(Config.SUCCESS_CODE,"");
		try{
			userInfoService.addUserInfo(userInfo);
		}
		catch(Exception e){
			logger.error(e.getMessage());
			result.setCode(Config.FAIL_CODE);
			return result;
		}

		return result;
	}
	
	@RequestMapping(value="getUserList",method=RequestMethod.GET)
	@ResponseBody
	public Result getCurrentUserInfo(HttpServletRequest request){
		Result result=new Result(Config.SUCCESS_CODE,"");
		try{
		   List<User> list=userService.getAllUser();
		   result.setRow(list);
		}
		catch(Exception e){
			e.printStackTrace();
			result.setCode(Config.FAIL_CODE);
			return result;
		}
		return result;
	}
	
	
}
